import {AfterViewInit, Component, OnInit, OnDestroy, ViewEncapsulation} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {MessagerService} from 'ng-easyui/components/messager/messager.service';
import {Goods} from '../../../globalModel/Goods';
import {GoodsService} from '../../../service/goods.service';
import {CoverService} from '../../../service/cover.service';
import {TreeUtil} from '../../../globalUtil/treeUtil';
import {Cover} from '../../../globalModel/Cover';
import {Subscription} from 'rxjs';
import {AdminService} from '../../../service/admin.service';

@Component({
  selector: 'app-goods',
  templateUrl: './goods.component.html',
  styleUrls: ['./goods.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class GoodsComponent implements OnInit, OnDestroy, AfterViewInit {
  componentTitle = '商品管理'; // 组件标题
  adminVariableSubscription: Subscription = null; // 订阅对象
  // eui-datagrid（数据表格）
  loading = true; // 开启加载提示
  loadMsg = '正在加载..';
  data = []; // 表格数据
  total = 0;
  pageNumber = 1;
  pageSize = 20;
  pageOptions = {
    pageList: [10, 20, 30, 40, 50],
    displayMsg: '当前 {from} 到 {to} , 共 {total} 条',
    layout: ['list', 'sep', 'first', 'prev', 'sep', 'tpl', 'sep', 'next', 'last', 'sep', 'refresh', 'sep', 'links', 'info']
  };
  selectRow = []; // 存储点击某一行后选中的行（数组）
  editRow: Goods = new Goods(); // 存储当前正在编辑的数据
  itemForPage: Goods = {parentIds: [], name: null, isActive: 'all', isRecommend: 'all'}; // 分页查询条件参数(双向数据绑定)
  // eui-dialog（添加、编辑）
  editDlgTitle = '添加、编辑商品信息';
  editDlgClosed = true; // 默认关闭弹框,false打开弹框
  goodsTypeData = []; // 商品类别数据(comboTree)
  parentId = null; // 选中的商品类别id
  coverTypeData = []; // 封面类别数据(comboTree)
  coverSrc = null; // 选中的封面地址
  // 表单
  itemForForm: FormGroup = null; // 表单对象
  formBtnDisabled = false; // 默认激活表单提交,true禁用表单提交
  placeholder = {
    name: {'title': '名称', 'prompt': '(2~20位有效字符)'},
    introduce: {'title': '说明', 'prompt': '(0~50位有效字符)'},
    src: {'title': '封面地址', 'prompt': '(1~500位有效字符)'},
    price: {'title': '价格', 'prompt': '(88.88)'},
    promotionPrice: {'title': '活动价格', 'prompt': '88.88'},
  };

  /**
   * 构造函数
   */
  constructor(
    private service: GoodsService,
    private coverService: CoverService,
    private formBuilder: FormBuilder,
    private messagerService: MessagerService,
    private adminService: AdminService) {
    // 创建表单对象
    this.createItemForForm();
    /**
     * 监听父组件推送的消息
     */
    this.adminVariableSubscription = adminService.adminObservable.subscribe(adminVariable => {
      /**
       * 删除回调事件
       */
      if (adminVariable.componentName === 'admin' && adminVariable.deleteSuccess !== null) {
        this.selectRow = []; // 取消选中的行
        if (adminVariable.deleteSuccess) {
          // 删除成功
          this.onPageChange({pageNumber: this.pageNumber, pageSize: this.pageSize}); // 重置当前页数据
        }
      }
    });
  }

  /**
   * 初始化函数
   */
  ngOnInit() {
  }

  /**
   * 组件销毁
   */
  ngOnDestroy() {
    if (this.adminVariableSubscription) {
      this.adminVariableSubscription.unsubscribe(); // 取消订阅,防止内存泄漏
    }
  }

  /**
   * 在组件相应的视图初始化之后调用
   */
  ngAfterViewInit() {
    // 查询商品类别信息
    this.service.selectGoodsType({}).subscribe(goodsTypeJson => {
      if (goodsTypeJson.code === 0) {
        this.goodsTypeData = TreeUtil.prototype.mergeByParentId(goodsTypeJson.data);
      }
    }, () => {
    }, () => {
      // 查询封面类别信息，包含封面信息
      this.coverService.selectCoverTypeJoinCover({}).subscribe(CoverTypeJoinCoverJson => {
        this.coverTypeData = CoverTypeJoinCoverJson.data;
      });
    });
    // 分页插件回调函数
    this.onPageChange({pageNumber: 1, pageSize: this.pageSize});
  }

  /**
   * 分页插件回调函数
   */
  onPageChange(event) {
    if (event.pageNumber > 0) {
      this.pageNumber = event.pageNumber;
      this.pageSize = event.pageSize;
      this.selectGoodsByPage();
    }
  }

  /**
   * 分页查询商品信息
   */
  selectGoodsByPage() {
    this.service.selectGoodsByPage(this.itemForPage, this.pageNumber, this.pageSize).subscribe(responseJson => {
      this.loading = false; // 关闭加载提示
      if (responseJson.code === 0) {
        this.data = responseJson.data.list;
        this.total = responseJson.data.total;
      }
    });
  }

  /**
   * 筛选
   */
  onScreening(): void {
    if (this.itemForPage.name === '') {
      this.itemForPage.name = null;
    }
    this.onPageChange({pageNumber: 1, pageSize: this.pageSize});
  }

  /**
   * 打开删除弹框
   */
  onOpenDeleteDlg(param): void {
    let id;
    if (param === 'deleteMore') {
      // 删除所选
      if (this.selectRow.length > 0) {
        id = this.selectRow.map(row => row.id).join(',');
        this.adminService.pushAdminVariable({componentName: 'goods', deleteDlgClosed: false, id: id});
      } else {
        this.messagerService.alert({title: '温馨提示', msg: '请先选中需要删除的数据!', ok: '确定'});
      }
    } else {
      // 删除所有
      id = 'all';
      this.adminService.pushAdminVariable({componentName: 'goods', deleteDlgClosed: false, id: id});
    }
  }

  /**
   * 点击添加按钮打开添加弹框
   * 双击行打开编辑弹框
   * @param param
   */
  onOpenEditDlg(param): void {
    this.selectRow = []; // 取消点击选中的行
    if (param === 'add') {
      /*
        添加
       */
      this.editDlgTitle = '添加封面信息';
    } else {
      /*
        编辑
       */
      this.editDlgTitle = '编辑封面信息';
      this.editRow = param;
      this.parentId = param.parentId; // 回显
      this.coverSrc = param.src; // 回显
    }
    this.createItemForForm(); // 创建表单对象
    this.editDlgClosed = false; // 打开弹框
  }

  /**
   * 创建表单对象
   */
  createItemForForm(): void {
    this.itemForForm = this.formBuilder.group({
      'name': [this.editRow.name, [Validators.required, Validators.pattern('^.{1,20}$')]],
      'price': [this.editRow.price, [Validators.required, Validators.pattern('^[0-9]+(\\.[0-9]{0,2})?$')]],
      'promotionPrice': [this.editRow.promotionPrice, [Validators.pattern('^[0-9]+(\\.[0-9]{0,2})?$')]],
      'introduce': [this.editRow.introduce, [Validators.pattern('^.{0,50}$')]],
    });
    if (this.editRow.id) {
      /*
        编辑
       */
      this.itemForForm.addControl('isActive',
        new FormControl(this.editRow.isActive, [Validators.pattern('^["0"|"1"].*$')]));
      this.itemForForm.addControl('isRecommend',
        new FormControl(this.editRow.isRecommend, [Validators.pattern('^["0"|"1"].*$')]));
    } else {
      /*
        添加
       */
    }
  }

  /**
   * 保存添加、编辑-提交表单
   */
  onSubmitForm(itemForForm): void {
    this.formBtnDisabled = true; // 禁用表单提交
    itemForForm.value.parentId = this.parentId; // 设置商品类别编号
    itemForForm.value.src = this.coverSrc; // 设置封面地址
    if (this.editRow.id) {
      /*
        编辑状态
       */
      itemForForm.value.id = this.editRow.id; // 设置ID作为后台修改的凭证
      if (itemForForm.value.name === this.editRow.name) { // 如果封面名称没有修改则需要设置为空
        itemForForm.value.name = null;
      }
    }
    this.service.modifyGoods(itemForForm.value).subscribe(responseJson => {
      if (responseJson.code === 0) {
        /*
          操作成功
         */
        this.onPageChange({pageNumber: this.pageNumber, pageSize: this.pageSize}); // 更新当前分页信息
        this.editDlgClosed = true; // 关闭弹框
      } else {
        /*
          操作失败
         */
        this.formBtnDisabled = false; // 激活表单提交按钮
      }
    });
  }

  /**
   * 刷新首页数据
   */
  onReLoad(): void {
    this.reset();
    this.onPageChange({pageNumber: 1, pageSize: this.pageSize});
  }

  /**
   * 取消添加、编辑
   */
  onEditCancel(): void {
    this.editDlgClosed = true; // 关闭添加、删除弹框
  }

  /**
   * 关闭弹框
   */
  onCloseDlg(): void {
    this.reset();
  }

  /**
   * 清空筛选条件
   */
  onResetScreening(): void {
    this.reset();
  }

  /**
   * 重置全局参数
   */
  reset(): void {
    this.editRow = new Cover();
    this.editDlgClosed = true;
    this.selectRow = [];
    this.formBtnDisabled = false;
    this.itemForPage = {parentIds: [], name: null, isActive: 'all', isRecommend: 'all'};
    this.coverSrc = null;
    this.parentId = null;
  }

  /**
   * 样式定义
   */
  setIsActiveCellCss(row, value) {
    if (value === '0') {
      return {color: 'blue'};
    }
  }

  setIsRecommendCellCss(row, value) {
    if (value === '0') {
      return {color: 'green'};
    }
  }

}
